package ai.leinao.notify.core;

import ai.leinao.notify.core.enums.NotifyType;
import ai.leinao.notify.core.configuration.ResourceNotifyProperties;
import ai.leinao.notify.core.template.AbstractTemplateRegistry;
import ai.leinao.notify.core.template.TemplateProperties;
import ai.leinao.notify.core.template.TemplateProvider;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;

/**
 * 基于配置文件形式的模板管理器
 *
 * @author zhong.wang
 * @date 2025/7/8
 */
@Getter
@Setter
public class ResourceTemplateRegistry extends AbstractTemplateRegistry implements SmartInitializingSingleton {
    /**
     * 资源模板管理器
     */
    private final ResourceNotifyProperties resourceNotifyProperties;

    /**
     * Spring上下文
     */
    private final ApplicationContext applicationContext;

    /**
     * 构造函数
     * @param resourceNotifyProperties
     */
    public ResourceTemplateRegistry(ResourceNotifyProperties resourceNotifyProperties, ApplicationContext applicationContext) {
        this.resourceNotifyProperties = resourceNotifyProperties;
        this.applicationContext = applicationContext;
    }

    /**
     * 根据通知类型和模板id获取模板属性
     *
     * @param notifyType
     * @param templateId
     * @return
     */
    @Override
    protected TemplateProperties getProperties(NotifyType notifyType, String templateId) {
        return resourceNotifyProperties.getTemplateProperties(notifyType.getType(), templateId);
    }

    /**
     * 模板提供者注册
     */
    @Override
    public void afterSingletonsInstantiated() {
        applicationContext.getBeanProvider(TemplateProvider.class)
                .forEach(this::registerProvider);
    }
}
